﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.ServiceModel.DomainServices.Client;
using RIA.Web.Models;
using RIA.Web.Services;
using System.Diagnostics;

namespace RIA.Views
{
	public partial class Demo : Page
	{
		NorthWindContext context = new NorthWindContext();

		public Demo()
		{
			InitializeComponent();
		}

		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			EntityQuery<Customer> query = context.GetCustomersQuery();
			
			///Load all
			//context.Load<Customer>(query);
			//this.dataGrid1.ItemsSource = context.Customers;

			var  q = from c in query where c.City.StartsWith("B") orderby c.CustomerID select c;
			context.Load<Customer>(q);
			this.dataGrid2.ItemsSource = context.Customers;
		}

		private void Invoke_Click(object sender, RoutedEventArgs e)
		{
			context.CalculateVacationBonus(DateTime.Now, t => {
				if (t.HasError)
				{
					MessageBox.Show(string.Format("Method Failed: {0}", t.Error.Message));
					t.MarkErrorAsHandled();
				}
				else
				{
					//t.UserState
					Debug.WriteLine(t.Value);
				}
			}, null);
		}

		NorthWindContext myctx = new NorthWindContext();
		private void hBind_Click(object sender, RoutedEventArgs e)
		{
			var q = myctx.GetCustomersQuery().Take(1);
			myctx.Load<Customer>(q, t =>
			{
				if (myctx.Customers.Count < 0) return;
				this.handBind.DataContext = myctx.Customers.First();
			}, null);
		}

		private void SpecialCascadedUpdate_Click(object sender, RoutedEventArgs e)
		{
			if (this.myctx.HasChanges)
			{
				///服务端先执行UpdateCustomer，然后执行SpecialCascadedUpdate
				this.myctx.SpecialCascadedUpdate(this.handBind.DataContext as Customer);
				this.myctx.SubmitChanges();
			}
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			NorthWindContext lctx = new NorthWindContext();
			var q = lctx.GetCustomersQuery().Take(1);
			lctx.Load<Customer>(q, t =>
			{
				if (lctx.Customers.Count < 0) return;
				var c = lctx.Customers.First();
				c.Address = c.Address + "aa";

				if (lctx.HasChanges)
				{
					///服务端先执行UpdateCustomer，然后执行SpecialCascadedUpdate
					lctx.SpecialCascadedUpdate(c);
					lctx.SubmitChanges();
				}
			}, null);
		}

	}
}
